package development;

import iplayparticle.view.iplayparticleResources;
import state.DrawListener;
import state.GameAlert;
import state.GameConstants;
import state.GameForm;
import state.GameGlobal;
import state.GameImage;
import state.Graphics;
import state.Key;
import state.Sprite;
import state.TimerListener;
import state.TouchScreenListener;
import state.component.BottomBar;
import state.component.Event;
import state.component.EventListener;
import state.component.GameMenu;
import state.component.MenuItem;
import state.component.MultiTab;
import state.component.TextField;
import state.font.FontManager;
import state.font.ImageText;
import state.util.GameColor;
import state.util.Hashtable;
import state.util.ImageUtil;
import state.util.NumberUtil;
import state.util.TwoDimensionInt;
import state.util.array.IntArray;
import state.util.array.StringArray;
import development.bean.User;
import development.group.FrmGroupListTableFreeUserChat;
import development.group.FrmGroupMenu;
import development.group.FrmGroupTableFreeUserFriend;
import development.socket.SocketClientUtil;

public class FrmTable extends GameForm implements TimerListener, EventListener, TouchScreenListener {
  public final String DAT_CUOC_LABEL = "Thiết lập bàn";
  
  public final String KICK_USER_LABEL = "Kick";

  private final int MAX_WAIT_TIME = 100; // 10s
  private final int MAX_START_TIME = 150; // 15s
  
  public static boolean dontNeedToConfig;
  public boolean isShowSettingBoard;
  public boolean isConfigTableDone;

  private GameImage numberBgImage;
  private GameImage leftStatusImage;
  private GameImage rightStatusImage;
  private GameImage ballImage;
  private GameImage popupImage;
  private GameImage buttonImage;

  private String[] nameUsers;

  private ImageText text8;

  private int selectItemIndexInBoard;
  private boolean isReadyToStart;
  private int inRoomTime;
  private boolean isSendReady;
  private boolean isStartGame;
  private int waitToStartGameTime;
  private String title;
  private GameImage chatImage;

  private TextField passwordTextField;
  private TextField bidTextField;
  private Sprite confirmButtonSprite;
  private GameMenu menu;
  private int titleMoveCount;
  private int count;
  
  private Sprite chatSprite;

  private static GameForm singleton;

  public static GameForm instance() {
    if (singleton == null) {
      singleton = new FrmTable();
    }
    return singleton;
  }

  public void init(Hashtable parameters) {
    for (int i = 0; i < Global.tableUsers.size(); i++) {
      User user = (User) Global.tableUsers.elementAt(i);
      SocketClientUtil.requestUserInfo(user.getName());
    }

    _manager.setBackGroundColor(0x440000);
    title = Global.currentGame.getName() + " - Phòng " + Global.currentRoom.getName() + " - Bàn " + Global.currentTable.getName();

    isStartGame = false;
    waitToStartGameTime = -1;

    selectItemIndexInBoard = 2;
    isReadyToStart = false;
    inRoomTime = 0;
    isSendReady = false;
    titleMoveCount = 0;
    count = 0;

    text8 = FontManager.getFont(FontManager.FONT_SIZE_8);

    ballImage = ImageUtil.getImage(Constants.NEW_IMAGE_CATEGORY, "datcuoc.png");
    numberBgImage = ImageUtil.getImage(Constants.NEW_IMAGE_CATEGORY, "Nen_So.png");
    leftStatusImage = ImageUtil.getImage(Constants.NEW_IMAGE_CATEGORY, "Chat.png");
    rightStatusImage = ImageUtil.getImage(Constants.NEW_IMAGE_CATEGORY, "Chat1.png");
    popupImage = ImageUtil.getImage(Constants.NEW_IMAGE_CATEGORY, "bg_popup.png");
    chatImage = ImageUtil.getImage(Constants.MENU_IMAGE_CATEGORY, "2.Chat.png");
    chatImage = ImageUtil.resizeImage2(chatImage, 25, 25);
    buttonImage = new GameImage(iplayparticleResources.image_button, null, null);

    bidTextField = new TextField(_manager, TextField.CONSTRAINT_NUMERIC, Constants.TEXT_FIELD_STYLE);
    bidTextField.setSize(99, 17);
    passwordTextField = new TextField(_manager, TextField.CONSTRAINT_PASSWORD, Constants.TEXT_FIELD_STYLE);
    passwordTextField.setSize(99, 17);
    setTextBid(Global.currentRoom.getMinBid());
    if (Constants.IS_240x320_SCREEN) {
      confirmButtonSprite = new Sprite(buttonImage, _manager, Constants.SCREEN_WIDTH / 2, 183, Constants.TOP_HCENTER_ANCHOR);
    } else {
      confirmButtonSprite = new Sprite(buttonImage, _manager, Constants.SCREEN_WIDTH / 2, 158, Constants.TOP_HCENTER_ANCHOR);
    }
    bidTextField.setPosition(Constants.SCREEN_WIDTH / 2 - bidTextField.getWidth() / 2, 86);
    passwordTextField.setPosition(Constants.SCREEN_WIDTH / 2 - passwordTextField.getWidth() / 2, 128);
    
    confirmButtonSprite.setVisible(false);
    confirmButtonSprite.setTouchScreenListener(this);
    confirmButtonSprite.setDrawListener(new DrawListener() {
      public void paint(Sprite source, Graphics g) {
        if (selectItemIndexInBoard == 2) {
          text8.drawString2(g, "Thiết lập", GameColor.YELLOW_CODE, source.getRealX() + source.getWidth() / 2, source.getRealY() + 2, Constants.TOP_HCENTER_ANCHOR);
        } else {
          text8.drawString2(g, "Thiết lập", GameColor.WHITE_CODE, source.getRealX() + source.getWidth() / 2, source.getRealY() + 2, Constants.TOP_HCENTER_ANCHOR);
        }
      }
    });
    updateFocus();
    
    chatSprite = new Sprite(chatImage, _manager, 2, 27, Constants.TOP_LEFT_ANCHOR);
    chatSprite.setTouchScreenListener(this);
    
    // Create bottom bar
    menu = new GameMenu(null, new String[] { "Mời chơi", "Bạn bè", "Thông tin TK" }, 3, this, Constants.MENU_STYLE, 0, GameConstants.SCREEN_HEIGHT - 45);

    if (Global.currentUser.getName().equals(Global.currentTable.getTableMasterName()) && !dontNeedToConfig) {
      isShowSettingBoard = true;
      isConfigTableDone = false;
    }
    dontNeedToConfig = true;
    setTimerListener(this);
    
    TwoDimensionInt CHAT_LOCATION_240x320 = new TwoDimensionInt(2, 6);
    CHAT_LOCATION_240x320.setRow(0, new IntArray(new int[] {26, 220}, 2));
    CHAT_LOCATION_240x320.setRow(1, new IntArray(new int[] {130, 54}, 2));
    CHAT_LOCATION_240x320.setRow(2, new IntArray(new int[] {130, 220}, 2));
    CHAT_LOCATION_240x320.setRow(3, new IntArray(new int[] {26, 54}, 2));
    CHAT_LOCATION_240x320.setRow(4, new IntArray(new int[] {26, 130}, 2));
    CHAT_LOCATION_240x320.setRow(5, new IntArray(new int[] {130, 130}, 2));
    
    TwoDimensionInt CHAT_LOCATION_320x240 = new TwoDimensionInt(2, 6);
    CHAT_LOCATION_320x240.setRow(0, new IntArray(new int[] {34, 154}, 2));
    CHAT_LOCATION_320x240.setRow(1, new IntArray(new int[] {190, 58}, 2));
    CHAT_LOCATION_320x240.setRow(2, new IntArray(new int[] {190, 154}, 2));
    CHAT_LOCATION_320x240.setRow(3, new IntArray(new int[] {34, 58}, 2));
    CHAT_LOCATION_320x240.setRow(4, new IntArray(new int[] {90, 154}, 2));
    CHAT_LOCATION_320x240.setRow(5, new IntArray(new int[] {90, 58}, 2));
    
    SocketClientUtil.joinChatRoom(CHAT_LOCATION_240x320, CHAT_LOCATION_320x240);
  }

  public void draw(Graphics g) {
    DrawUtils.drawBackground(g);
    
    count++;
    if (count % 3 == 0) {
      titleMoveCount++;
      titleMoveCount = titleMoveCount % (title.length() - 1);
    }
    FrmGroupTableFreeUserFriend groupTableFreeUserFriend = (FrmGroupTableFreeUserFriend) FrmGroupTableFreeUserFriend.instance();
    groupTableFreeUserFriend.getMultiTab().setTitle(0, title.substring(titleMoveCount));
    
    text8.drawString2(g, title, GameColor.WHITE_CODE, Constants.SCREEN_WIDTH / 2, 5, Constants.TOP_HCENTER_ANCHOR);

    // Vẽ ceilling của bàn
    g.drawImage(ballImage, GameConstants.SCREEN_WIDTH / 2, GameConstants.SCREEN_HEIGHT / 2 - 10, GameConstants.CENTER_ANCHOR);
    text8.drawString2(g, "Đặt cược", GameColor.WHITE_CODE, GameConstants.SCREEN_WIDTH / 2, GameConstants.SCREEN_HEIGHT / 2 - 25, GameConstants.TOP_HCENTER_ANCHOR);
    text8.drawString2(g, String.valueOf(Global.currentTable.getBid()), GameColor.WHITE_CODE, GameConstants.SCREEN_WIDTH / 2, GameConstants.SCREEN_HEIGHT / 2 - 10, GameConstants.TOP_HCENTER_ANCHOR);

    setBottomBarMenu(g);
    if (GameConstants.IS_240x320_SCREEN) {
      draw240320(g);
    } else {
      draw320x240(g);
    }

    if (!isShowSettingBoard) {
      Global.drawChat(g);
    }
  }
  
  private void setBottomBarMenu(Graphics g) {
    DrawUtils.getBottomBar(FrmGroupTableFreeUserFriend.instance().getManager()).setLeftMenu("", null);
    if (isShowSettingBoard) {
      if (selectItemIndexInBoard == 2) {
        DrawUtils.setBottomBar(FrmGroupTableFreeUserFriend.instance().getManager(), "", "Thiết lập", "Hủy");
      } else {
        DrawUtils.setBottomBar(FrmGroupTableFreeUserFriend.instance().getManager(), "Xóa", "", "Hủy");
      }
      return;
    }
    
    if (Global.isShowedInputChatBox()) {
      DrawUtils.setBottomBar(FrmGroupTableFreeUserFriend.instance().getManager(), "Trở về", "Gửi", "Xóa");
      DrawUtils.getBottomBar(FrmGroupTableFreeUserFriend.instance().getManager()).setLeftMenu("Trở về", null);
      return;
    }
    
    DrawUtils.getBottomBar(FrmGroupTableFreeUserFriend.instance().getManager()).setLeftMenu("Menu", menu);
    DrawUtils.getBottomBar(FrmGroupTableFreeUserFriend.instance().getManager()).setRightLabel("Trở về");
    if (Global.currentUser.getName().equals(Global.currentTable.getTableMasterName())) {
      if (isReadyToStart) {
        DrawUtils.getBottomBar(FrmGroupTableFreeUserFriend.instance().getManager()).setCenterLabel("Bắt đầu");
      } else {
        DrawUtils.getBottomBar(FrmGroupTableFreeUserFriend.instance().getManager()).setCenterLabel("");
        text8.drawString2(g, "Bắt đầu", 0x969696, GameConstants.SCREEN_WIDTH / 2, GameConstants.SCREEN_HEIGHT - 4, GameConstants.BOTTOM_HCENTER_ANCHOR);
      }
    } else {
      if (!Global.currentUser.isReady()) {
        DrawUtils.getBottomBar(FrmGroupTableFreeUserFriend.instance().getManager()).setCenterLabel("Sẵn sàng");
      } else {
        DrawUtils.getBottomBar(FrmGroupTableFreeUserFriend.instance().getManager()).setCenterLabel("");
      }
    }
  }

  public void draw240320(Graphics g) {
    if (isShowSettingBoard) {
      g.drawImage(popupImage, GameConstants.SCREEN_WIDTH / 2, 80, GameConstants.TOP_HCENTER_ANCHOR);
      text8.drawString2(g, "Đặt cược", GameColor.WHITE_CODE, GameConstants.SCREEN_WIDTH / 2, 92, GameConstants.TOP_HCENTER_ANCHOR);
      text8.drawString2(g, "Đặt mật khẩu", GameColor.WHITE_CODE, GameConstants.SCREEN_WIDTH / 2, 135, GameConstants.TOP_HCENTER_ANCHOR);
      bidTextField.setVisible(true);
      passwordTextField.setVisible(true);
      confirmButtonSprite.setVisible(true);
      return;
    }
    bidTextField.setVisible(false);
    passwordTextField.setVisible(false);
    confirmButtonSprite.setVisible(false);

    // Draw user
    drawUser(g, 0, 26, 220, 84, 206, 54, 198, leftStatusImage);
    drawUser(g, 1, 176, 54, 160, 40, 130, 32, rightStatusImage);
    drawUser(g, 2, 176, 220, 160, 206, 130, 198, rightStatusImage);
    drawUser(g, 3, 26, 54, 84, 40, 54, 32, leftStatusImage);
    drawUser(g, 4, 26, 130, 84, 116, 54, 108, leftStatusImage);
    drawUser(g, 5, 176, 130, 160, 116, 130, 108, rightStatusImage);

    if (Global.currentUser.getName().equals(Global.currentTable.getTableMasterName())) {
      if ((waitToStartGameTime > -1) && (waitToStartGameTime <= MAX_START_TIME)) {
        g.drawImage(numberBgImage, 77, 219, GameConstants.CENTER_ANCHOR);
        text8.drawString2(g, String.valueOf((MAX_START_TIME - waitToStartGameTime) / 10), GameColor.WHITE_CODE, 77, 219, GameConstants.CENTER_ANCHOR);
      }
    } else {
      if ((inRoomTime <= MAX_WAIT_TIME) && !Global.currentUser.isReady()) {
        g.drawImage(numberBgImage, 77, 219, GameConstants.CENTER_ANCHOR);
        text8.drawString2(g, String.valueOf((MAX_WAIT_TIME - inRoomTime) / 10), GameColor.WHITE_CODE, 77, 219, GameConstants.CENTER_ANCHOR);
      }
    }
  }

  public void draw320x240(Graphics g) {
    if (isShowSettingBoard) {
      g.drawImage(popupImage, GameConstants.SCREEN_WIDTH / 2, 65, GameConstants.TOP_HCENTER_ANCHOR);
      text8.drawString2(g, "Đặt cược", GameColor.WHITE_CODE, GameConstants.SCREEN_WIDTH / 2, 70, GameConstants.TOP_HCENTER_ANCHOR);
      text8.drawString2(g, "Đặt mật khẩu", GameColor.WHITE_CODE, GameConstants.SCREEN_WIDTH / 2, 110, GameConstants.TOP_HCENTER_ANCHOR);
      bidTextField.setVisible(true);
      passwordTextField.setVisible(true);
      confirmButtonSprite.setVisible(true);
      return;
    }
    bidTextField.setVisible(false);
    passwordTextField.setVisible(false);
    confirmButtonSprite.setVisible(false);

    // Draw user
    drawUser(g, 0, 34, 154, 92, 140, 63, 133, leftStatusImage);
    drawUser(g, 1, 242, 58, 225, 44, 197, 36, rightStatusImage);
    drawUser(g, 2, 242, 154, 225, 140, 197, 133, rightStatusImage);
    drawUser(g, 3, 34, 58, 92, 44, 63, 36, leftStatusImage);
    drawUser(g, 4, 114, 154, 172, 140, 143, 133, leftStatusImage);
    drawUser(g, 5, 114, 58, 172, 44, 143, 36, leftStatusImage);

    if (Global.currentUser.getName().equals(Global.currentTable.getTableMasterName())) {
      if ((waitToStartGameTime > -1) && (waitToStartGameTime <= MAX_START_TIME)) {
        g.drawImage(numberBgImage, 80, 160, GameConstants.CENTER_ANCHOR);
        text8.drawString2(g, String.valueOf((MAX_START_TIME - waitToStartGameTime) / 10), GameColor.WHITE_CODE, 80, 160, GameConstants.CENTER_ANCHOR);
      }
    } else {
      if ((inRoomTime <= MAX_WAIT_TIME) && !Global.currentUser.isReady()) {
        g.drawImage(numberBgImage, 80, 160, GameConstants.CENTER_ANCHOR);
        text8.drawString2(g, String.valueOf((MAX_WAIT_TIME - inRoomTime) / 10), GameColor.WHITE_CODE, 80, 160, GameConstants.CENTER_ANCHOR);
      }
    }
  }

  private void drawUser(Graphics g, int userIndex, int avatarX, int avatarY, int textX, int textY, int chatX, int chatY, GameImage statusImage) {
    if (userIndex > Global.tableUsers.size() - 1) {
      return;
    }

    User user = ((User) Global.tableUsers.elementAt(userIndex));
    g.drawImage(statusImage, chatX, chatY, GameConstants.TOP_LEFT_ANCHOR);

    if (user.getName().equals(Global.currentTable.getTableMasterName())) {
      text8.drawString2(g, "Chủ phòng", GameColor.YELLOW_CODE, textX, textY, GameConstants.CENTER_ANCHOR);
    } else {
      if (user.isReady()) {
        text8.drawString2(g, "Sẵn sàng", GameColor.WHITE_CODE, textX, textY, GameConstants.CENTER_ANCHOR);
      }
    }
    g.drawImage(Global.getAvatar(user.getName()), avatarX, avatarY, GameConstants.TOP_LEFT_ANCHOR);
    text8.drawString2(g, user.getName(), GameColor.WHITE_CODE, avatarX - 2, avatarY + 37, GameConstants.TOP_LEFT_ANCHOR);
    text8.drawString2(g, user.getGold() + " gold", GameColor.YELLOW_CODE, avatarX + 1, avatarY + 49, GameConstants.TOP_LEFT_ANCHOR);
  }
  
  public void checkToAddSubMenu() {
    // "Mời chơi", "Bạn bè", "Thông tin TK"
    GameMenu menu1 = DrawUtils.getBottomBar(FrmGroupTableFreeUserFriend.instance().getManager()).getLeftMenu();
    if (menu1 == null) {
      return;
    }
    
    menu1.removeAll();
    menu1.addItem("Mời chơi");
    if (Global.currentUser.getName().equals(Global.currentTable.getTableMasterName())) {
      menu1.addItem(DAT_CUOC_LABEL);
    }
    menu1.addItem("Bạn bè");
    
    // Add sub menu for user info
    MenuItem userInfoMenuItem = menu1.addItem("Thông tin TK");
    if (Global.tableUsers.size() > 1) {
      // Create user list
      nameUsers = new String[Global.tableUsers.size() - 1];
      int count1 = 0;
      for (int i = 0; i < Global.tableUsers.size(); i++) {
        if (!((User) Global.tableUsers.elementAt(i)).getName().equals(Global.currentUser.getName())) {
          nameUsers[count1] = ((User) Global.tableUsers.elementAt(i)).getName();
          count1++;
        }
      }
      
      // Add sub menu for add friend
      MenuItem menuItem = menu1.addItem("Kết bạn");
      menuItem.addItems(new StringArray(nameUsers, Global.tableUsers.size() - 1));
      
      // Add sub menu for kick
      if (Global.currentUser.getName().equals(Global.currentTable.getTableMasterName())) {
        menuItem = menu1.addItem(KICK_USER_LABEL);
        menuItem.addItems(new StringArray(nameUsers, Global.tableUsers.size() - 1));
      }
      
      // Add sub menu for user info
      userInfoMenuItem.addItems(new StringArray(nameUsers, Global.tableUsers.size() - 1));
    }
    menu1.changeIndexToIndex(0);
  }
  
  public void keyReleasedForSettingBoard(int keyCode) {
    switch (keyCode) {
    case Key.SOFT_LEFT:
      if (selectItemIndexInBoard == 0) {
        bidTextField.deleteLastChar();
      } else {
        passwordTextField.deleteLastChar();
      }
      break;
    case Key.SOFT_RIGHT:
      setTextBid(Global.currentTable.getBid());
      passwordTextField.setText("");
      isShowSettingBoard = false;
      break;
    case Key.FIRE:
      switch (selectItemIndexInBoard) {
      case 0:
        bidTextField.pointerReleased(bidTextField, bidTextField.getRealX(), bidTextField.getRealY());
        break;
      case 1:
        passwordTextField.pointerReleased(passwordTextField, passwordTextField.getRealX(), passwordTextField.getRealY());
        break;
      case 2:
        confirmSetting();
        break;
      }
      break;
    case Key.UP:
    case Key.LEFT:
      Global.hideInputChatBox();
      selectItemIndexInBoard = (--selectItemIndexInBoard < 0)? 0 : selectItemIndexInBoard;
      updateFocus();
      break;
    case Key.DOWN:
    case Key.RIGHT:
      Global.hideInputChatBox();
      selectItemIndexInBoard = (++selectItemIndexInBoard > 2)? 2 : selectItemIndexInBoard;
      updateFocus();
      break;
    default:
      if (selectItemIndexInBoard == 0) {
        bidTextField.keyReleased1(keyCode);
      } else if (selectItemIndexInBoard == 1) {
        passwordTextField.keyReleased1(keyCode);
      }
      break;
    }
  }
  
  public void keyReleased(int keyCode) {
    if (isShowSettingBoard) {
      keyReleasedForSettingBoard(keyCode);
      return;
    }
    
    // Check to show chat
    if (!Key.isCommandKey) {
      if (Global.chatComponent != null) {
        Global.chatComponent.setShowInputChatMessageTextField(true);
        Global.chatComponent.keyReleased(keyCode);
      }
      return;
    }
    
    // If chat box already show
    if (Global.isShowedInputChatBox()) {
      switch (keyCode) {
      case Key.SOFT_LEFT:
        Global.hideInputChatBox();
        break;
      case Key.FIRE:
        SocketClientUtil.sendMessage(Global.chatComponent.getCurrentRoomId(), Global.chatComponent.getChatTextField().getText());
        Global.hideInputChatBox();
        break;
      case Key.SOFT_RIGHT:
        Global.chatComponent.getChatTextField().deleteLastChar();
        break;
      }
      return;
    }
    
    switch (keyCode) {
    case Key.SOFT_RIGHT:
      SocketClientUtil.leaveTableRequest();
      GameGlobal.nextState(FrmGroupListTableFreeUserChat.instance(), null);
      break;
    case Key.FIRE:
      if (Global.currentUser.getName().equals(Global.currentTable.getTableMasterName())) {
        if (isReadyToStart) {
          SocketClientUtil.startGame();
        }
      } else {
        if (!Global.currentUser.isReady()) {
          SocketClientUtil.sendReady(true);
        }
      }
      break;
    }
  }
  
  private void confirmSetting() {
    isShowSettingBoard = false;
    Global.hideInputChatBox();
    int bid = getBid();
    if (selectItemIndexInBoard != 3) {
      if(Global.currentGame.getId().equals("bacay") && (Global.currentUser.getGold() < bid * 5)){
        GameGlobal.alert.showAlert2(this, GameAlert.OK_TYPE, "Không đủ tiền để tạo bàn", 98);
      } else if (bid > Global.currentUser.getGold()) {
        GameGlobal.alert.showAlert1(this, GameAlert.OK_TYPE, StringArray.create1( "Không thể đặt tiền cược", "lớn hơn số tiền bạn đang có" ), 98);
      } else {
        SocketClientUtil.configTable(bid, passwordTextField.getText());
      }
    }
  }
  
  public void pointerDragged(Sprite source, int x, int y) {
  }

  public void pointerPressed(Sprite source, int x, int y) {
  }

  public void pointerReleased(Sprite source, int x, int y) {
    if (source == chatSprite) {
      if ((Global.chatComponent != null) && !isShowSettingBoard) {
        Global.chatComponent.setShowInputChatMessageTextField(true);
        Global.chatComponent.getChatTextField().setText("");
        Global.chatComponent.getChatTextField().pointerReleased(Global.chatComponent.getChatTextField(), 0, 0);
      }
    } else if (source == confirmButtonSprite) {
      selectItemIndexInBoard = 2;
      updateFocus();
      keyReleased(Key.FIRE);
    }
  }
  
  private void updateFocus() {
    bidTextField.setFocused(false);
    passwordTextField.setFocused(false);
    switch (selectItemIndexInBoard) { 
    case 0:
      bidTextField.setFocused(true);
      break;
    case 1:
      passwordTextField.setFocused(true);
      break;
    }
  }
  
  private int getBid() {
    String bidStr = bidTextField.getText();
    if (bidStr.length() == 0) {
      bidStr = "0";
    }
    
    int bidInt = NumberUtil.parseInt(bidStr);
    if (bidInt == NumberUtil.ERROR_VALUE) {
      Global.alert.showAlert(this, GameAlert.OK_TYPE, "Tiền cược phải là số");
      setTextBid(Global.currentRoom.getMinBid());
      return 0;
    }
    return bidInt;
  }

  private boolean checkIfAllUserReady() {
    if (Global.tableUsers.size() <= 1) {
      return false;
    }
    boolean isAllUserReady = true;
    for (int i = 0; i < Global.tableUsers.size(); i++) {
      User user = (User) Global.tableUsers.elementAt(i);
      if (user.getName().equals(Global.currentTable.getTableMasterName())) {
        continue;
      }

      if (!user.isReady()) {
        isAllUserReady = false;
        break;
      }
    }
    return isAllUserReady;
  }
  
  private void setTextBid(int bid) {
    if (bid < 10) {
      bid = 10;
    }
    bidTextField.setText(String.valueOf(bid));
  }

  public void doTask() {
    if (Global.currentUser.getName().equals(Global.currentTable.getTableMasterName())) {
      isReadyToStart = checkIfAllUserReady();
      if (isReadyToStart && (!isShowSettingBoard || isConfigTableDone) && !isStartGame) {
        if (waitToStartGameTime == -1) {
          waitToStartGameTime = 0;
        }

        if (Global.tableUsers.size() < Global.currentTable.getMaxUser()) {
          waitToStartGameTime = -1;
        }

        if (waitToStartGameTime > -1) {
          waitToStartGameTime++;
          if (waitToStartGameTime > MAX_START_TIME) {
            isStartGame = true;
            SocketClientUtil.startGame();
          }
        }
      } else if (!isReadyToStart) {
        waitToStartGameTime = -1;
      }
    } else {
      inRoomTime++;
      if (inRoomTime > MAX_WAIT_TIME && !Global.currentUser.isReady() && !isSendReady) {
        isSendReady = true;
        SocketClientUtil.sendReady(true);
      }
    }
  }

  public void initToCheckReady() {
    isSendReady = false;
    inRoomTime = 0;
  }

  public void onActionPerform(Event event) {
    if (MultiTab.OPEN_TAB_EVENT.equals(event.getAction())) {
      BottomBar bottomBar = DrawUtils.getBottomBar(FrmGroupTableFreeUserFriend.instance().getManager());
      bottomBar.setLabels("Menu", "", "");
      bottomBar.setLeftMenu("Menu", menu);
      return;
    }
    
    // "Mời chơi", "Kết bạn", "Kick", "Bạn bè"
    String action = event.getAction();
    if (action.equals("Mời chơi")) {
      if (Global.tableUsers.size() >= Global.currentTable.getMaxUser()) {
        Global.alert.showAlert(this, GameAlert.OK_TYPE, "Bàn đã đầy");
      } else {
        FrmGroupTableFreeUserFriend.setTab(1);
      }
    } else if (action.equals("Bạn bè")) {
      FrmGroupTableFreeUserFriend.setTab(2);
    } else if (action.equals(DAT_CUOC_LABEL)) {
      isShowSettingBoard = true;
      setTextBid(Global.currentTable.getBid());
      isConfigTableDone = false;
    } else if (action.equals("Thông tin TK")) {
      FrmUserInfo.goBackForm = FrmGroupTableFreeUserFriend.instance();
      Global.nextState(FrmUserInfo.instance(), null);
    } else {
      if (event.getSource() instanceof MenuItem) {
        MenuItem currentMenu = (MenuItem) event.getSource();
        if (currentMenu.getParent().getLabel().equals("Kết bạn")) {
          // Trường hợp là menu kết bạn
          for (int i = 0; i < Global.tableUsers.size(); i++) {
            User user = (User) Global.tableUsers.elementAt(i);
            if (action.equals(user.getName())) {
              SocketClientUtil.addFriendRequest(action);
            }
          }
        } else if (currentMenu.getParent().getLabel().equals("Kick")) {
          // Trường hợp là menu kick
          for (int i = 0; i < Global.tableUsers.size(); i++) {
            User user = (User) Global.tableUsers.elementAt(i);
            if (action.equals(user.getName())) {
              SocketClientUtil.kickUserRequest(action);
            }
          }
        } else if (currentMenu.getParent().getLabel().equals("Thông tin TK")) {
          // Trường hợp là menu kick
          for (int i = 0; i < Global.tableUsers.size(); i++) {
            User user = (User) Global.tableUsers.elementAt(i);
            if (action.equals(user.getName())) {
              Hashtable parameters = new Hashtable();
              parameters.put("User", action);
              FrmUserInfo.goBackForm = FrmGroupTableFreeUserFriend.instance();
              Global.nextState(FrmUserInfo.instance(), parameters);
            }
          }
        }
      }
    }
  }

  public void alertEventPerform(int alertType, int eventType, int alertId) {
    if (alertId == 99) { // Trong trường hợp người chơi bị kick ra ngoài
      GameGlobal.nextState(FrmGroupListTableFreeUserChat.instance(), null);
    } else if (alertId == 98) { // Khi chủ bàn không đủ tiền để đặt tiền cược
      isShowSettingBoard = true;
      Global.hideInputChatBox();
    } else if (alertId == 97 && eventType == GameAlert.YES_BUTTON) {
      SocketClientUtil.leaveTableRequest();
      SocketClientUtil.leaveRoomRequest();
      GameGlobal.nextState(FrmGroupMenu.instance(), null);
    } else if (alertId == 10 && eventType == GameAlert.NO_BUTTON) { // Trường
      SocketClientUtil.leaveTableRequest();
      GameGlobal.nextState(FrmGroupListTableFreeUserChat.instance(), null);
    }
  }

  public void destroy() {
    nameUsers = null;
    title = null;

    text8 = null;
    numberBgImage = null;
    leftStatusImage = null;
    rightStatusImage = null;
    ballImage = null;
    popupImage = null;
    buttonImage = null;
    confirmButtonSprite = null;
    
    chatImage = null;
    menu = null;
    chatSprite = null;
  }
}
